<!-- 选择海报 -->
<template>
    <view class="page">
        <status-bar title='选择海报' :goHome='fromShare'></status-bar>
        <view class="padding30" v-if="list.length">
            <view class="p-re">
                <image :src="$imgUrls(list[current].poster)" mode="widthFix"></image>
                <view class="info p-ab">
                    <view class="inside bgwhite wh padding20 d-flex j-sb a-center">
                        <view>
                            <view class="d-flex m-bot40">
                                <u-avatar :src="$imgUrls(list[current].v_headimg)" size="50"></u-avatar>
                                <view class="m-left40 d-flex f-column j-sb p-top6 p-bot6">
                                    <view class="size28 bold">{{ list[current].v_name }}</view>
                                    <view class="size22 color_44 bold">{{ list[current].website_article_addtime }}</view>
                                    <view class="color_66 bold">
                                        <text class="size22 m-right10">{{ list[current].chineseCalendar.term }}</text>
                                        <text class="size22">{{ list[current].chineseCalendar.info }}</text>
                                    </view>
                                </view>
                            </view>
                            <view class="p-re">
                                <u-textarea v-model="value" height="42" placeholder="此处输入标语"></u-textarea>
                                <view class="load p-ab bor_radius flexac" @click="handleReload" v-if="sloganList.length">
                                    <u-icon name="reload" color="#FFF" size="15"></u-icon>
                                </view>
                            </view>
                        </view>
                        <view class="text-center">
                            <image :src="$imgUrls(list[current].qr_img)" show-menu-by-longpress mode="aspectFit" class="code"></image>
                            <view class="size22 color_22 m-top12">长按或扫码进入</view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="flexac m-top50 m-bot18">
                <view class="btn bgwhite bor_radius flexac f-column" @click="getPoster">
                    <u-icon name="download" color="#FF644E" size="24" bold></u-icon>
                    <text class="num h7 bold">{{ list[current].website_article_download > 99 ? '99+' : list[current].website_article_download }}</text>
                </view>
            </view>
        </view>

        <!-- 左右箭头 -->
        <view class="leftArrow bgwhite bor_radius flexac" v-if="current" @click="current--">
            <text class="iconfont icon-xiangzuo color_33"></text>
        </view>
        <view class="rightArrow bgwhite bor_radius flexac" v-if="current != list.length - 1" @click="current++">
            <text class="iconfont icon-xiangyouxiayiye"></text>
        </view>

        <canvas :style="{width: canvasWidth + 'px', height: canvasHeight + 'px'}" canvas-id="firstCanvas" id="firstCanvas"
            style="position: fixed; top: -9999px;"></canvas>
        
        <u-overlay :show="showOverlay" @click="showOverlay = false">
            <view class="overlay height flexac f-column" @tap.stop>
                <image :src="posterImg" mode="widthFix" show-menu-by-longpress class="viewbox5 m-bot30"></image>
                <u-icon name="close-circle" size="30" color="#fff" @click="showOverlay = false"></u-icon>    
		    </view>
        </u-overlay>
    </view>
</template>

<script>
import { mapState } from 'vuex'
export default {
    data(){
        return {
            fromShare: 0,
            value: '',
            cate_id: '', // 分类id
            list: [],
            current: 0, // 当前海报的下标
            sloganList: [],
            sloganI: 0,
            canvasWidth: 0,
            canvasHeight: 0,
            showOverlay: false,
            posterImg: ''
        }
    },
    computed:{
		...mapState(['System'])
	},
    onLoad(e){
        if(e.cate_id) this.cate_id = e.cate_id
        if(e.current) this.current = parseFloat(e.current)
        this.getList()
        this.getSlogan()
    },
    methods: {
        getList(){
            this.$http.get({
                url: '/PrivateSphereApi/getResource',
                data: {
                    type: 'poster',
                    website_list_id: this.cate_id
                }
            }).then(res=>{
                if(res.code != 200) return this.$Toast(res.msg)
                this.list = res.data || []
            })
        },
        getSlogan(){
            this.$http.get({
                url: '/PrivateSphereApi/getResource',
                data: {
                    type: 'slogan'
                }
            }).then(res=>{
                if(res.code != 200) return this.$Toast(res.msg)
                this.sloganList = res.data || []
                this.value = this.sloganList[0]?.website_article_info || ''
            })
        },
        handleReload(){
            let last = this.sloganList.length - 1
            this.sloganI = this.sloganI == last ? 0 : this.sloganI + 1
            this.value = this.sloganList[this.sloganI].website_article_info
        },
        recordDownload(){
            this.$http.get({
                url: '/PrivateSphereApi/incDownload',
                data: {
                    website_article_id: this.list[this.current].website_article_id
                }
            }).then(res=>{
                console.log(res)
            })
        },
        getLocalPath(url){ // 下载到本地返回临时路径
            return new Promise(resolve=>{
                uni.downloadFile({
                    url,
                    success(res){
                        resolve(res.tempFilePath)
                    }
                })
            })
        },
        getImgWh(src){ // 获取图片信息
            return new Promise(resolve=>{
                uni.getImageInfo({
                    src,
                    success(res){
                        resolve(res)
                    }
                })
            })
        },
        rpx2px(rpx){
            return rpx / 750 * this.System.windowWidth
        },
        multi(rpx){ // 放大画布的倍数(可更改)使图片更清晰
            return Math.round(this.rpx2px(rpx * 4))
        },
        roundRect(ctx, x, y, w, h, r){
            ctx.beginPath()
            ctx.moveTo(x+r, y)
            ctx.arcTo(x+w, y, x+w, y+h, r)
            ctx.arcTo(x+w, y+h, x, y+h, r)
            ctx.arcTo(x, y+h, x, y, r)
            ctx.arcTo(x, y, x+w, y, r)
            ctx.closePath()
        },
        breakTextLines(ctx, text, maxWidth){ // 文本换行
            let words = text.split('')
            let line = ''
            let lines = []
            for(let i = 0; i < words.length; i++){
                line = line + words[i]
                let metrics = ctx.measureText(line)
                if(metrics.width >= maxWidth){
                    lines.push(line)
                    line = ''
                }
            }
            if(line) lines.push(line)
            return lines
        },
        imgBaseUrl(img) {
            const reg = /^(http|https)/
            if(!img) return
            if(img.search(reg) != -1) return img
            return this.baseUrl + img
        },
        async getPoster(){
            let that = this
            that.$showLoading('海报生成中...')
            let info = that.list[that.current]
            let { multi } = that
            let ctx = uni.createCanvasContext('firstCanvas')
            // 背景
            let bgImg = await that.getLocalPath(that.imgBaseUrl(info.poster))
            let { width, height } = await that.getImgWh(bgImg)
            that.canvasWidth = multi(690)
            that.canvasHeight = multi(690 / width * height)
            ctx.drawImage(bgImg, 0, 0, that.canvasWidth, that.canvasHeight) // 位置宽高
            // 圆角矩形
            ctx.fillStyle = '#BFBFBF'
            that.roundRect(ctx, multi(17), multi(690 / width * height - 331), multi(656), multi(298), multi(14))
            ctx.fill()
            ctx.fillStyle = '#FFFFFF'
            that.roundRect(ctx, multi(23), multi(690 / width * height - 325), multi(644), multi(286), multi(8))
            ctx.fill()
            // 头像
            ctx.save()
            ctx.beginPath()
            ctx.arc(multi(93), multi(690 / width * height - 255), multi(50), 0, 2 * Math.PI)
            ctx.clip()
            let avatar = await that.getLocalPath(that.imgBaseUrl(info.v_headimg))
            ctx.drawImage(avatar, multi(43), multi(690 / width * height - 305), multi(100), multi(100))
            ctx.restore()
            // 文本（bug：y应算文本左下角）
            ctx.font = `bold ${multi(28)}px sans-serif`
            ctx.setFillStyle('#000')
            ctx.fillText(info.v_name, multi(183),  multi(690 / width * height - 269))
            ctx.font = `bold ${multi(22)}px sans-serif`
            ctx.setFillStyle('#444')
            ctx.fillText(info.website_article_addtime, multi(183), multi(690 / width * height - 241))
            ctx.font = `bold ${multi(22)}px sans-serif`
            ctx.setFillStyle('#666')
            ctx.fillText(`${info.chineseCalendar.term}  ${info.chineseCalendar.info}`, multi(183), multi(690 / width * height - 213))
            // 文本域
            ctx.font = `normal ${multi(24)}px sans-serif`
            ctx.setFillStyle('#000')
            let lines = that.breakTextLines(ctx, that.value, multi(397))
            lines.forEach((line, index)=>{
                if(index < 3) ctx.fillText(line, multi(49), multi(690 / width * height - 159 + (index + 1) * 28))
            })
            // 二维码
            let code = await that.getLocalPath(that.imgBaseUrl(info.qr_img))
            ctx.drawImage(code, multi(503), multi(690 / width * height - 262), multi(120), multi(120))
            ctx.setFontSize(multi(22))
            ctx.setFillStyle('#222')
            ctx.fillText('长按或扫码进入', multi(486), multi(690 / width * height - 108))

            ctx.draw(false, ()=>{ // 绘制完成后回调
                setTimeout(()=>{
                    uni.canvasToTempFilePath({ // 当前画布内容导出生成图片
                        canvasId: 'firstCanvas',
                        success(res){
                            that.getAuth(res.tempFilePath)
                            that.posterImg = res.tempFilePath
                            that.showOverlay = true
                            that.recordDownload() // 添加下载量
                            that.getList()
                        },
                        complete(){
                            that.$hideLoading()
                        }
                    })
                }, 100)
            })
        },
        getAuth(filePath){
            let that = this
            uni.getSetting({ 
                success(res){ // 获取用户授权结果
                    if(!res.authSetting['scope.writePhotosAlbum']){
                        uni.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success(){
                                that.savePoster(filePath)
                            }
                        })
                    } else{ // 已授权保存到相册
                        that.savePoster(filePath)
                    }
                }
            })
        },
        savePoster(filePath){
            let that = this
            uni.saveImageToPhotosAlbum({ // 保存图片到相册
                filePath,
                success(){
                    that.$Toast('请到手机相册查看海报')
                },
                fail(){
                    that.$Toast('保存失败')
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.page {
    background: #222;
}
.info {
    left: 17rpx;
    bottom: 33rpx;
    z-index: 10;
    width: 656rpx;
    height: 298rpx;
    background: #BFBFBF;
    padding: 6rpx;
    border-radius: 14rpx;
    .inside {
        border-radius: 8rpx;
    }
}
.code {
    width: 120rpx;
    height: 120rpx;
}
.load {
    right: -20rpx;
    top: -20rpx;
    z-index: 20;
    width: 40rpx;
    height: 40rpx;
    background: #FF4242;
}
.btn {
    width: 80rpx;
    height: 80rpx;
    .num {
        color: #FF644E; 
        margin-top: -4rpx;
    }
}
/deep/ .u-textarea {
    padding: 6rpx !important;
    width: 435rpx;
    .u-textarea__field {
        font-size: 24rpx;
        color: #000;
    }
}
.leftArrow {
    position: fixed;
    width: 66rpx;
    height: 66rpx;
    opacity: 0.8;
    top: 50%;
    margin-top: -33rpx;
    left: 30rpx;
    z-index: 20;
}
.rightArrow {
    position: fixed;
    width: 66rpx;
    height: 66rpx;
    opacity: 0.8;
    top: 50%;
    margin-top: -33rpx;
    right: 30rpx;
    z-index: 20;
    .icon-xiangyouxiayiye {
        color: #333 !important;
    }
}
.overlay {
    overflow-y: auto;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
}
</style>